package org.swingannotations.impl;

import java.awt.Component;
import java.awt.Container;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Vector;

/**
 * Given a awt.container, this knows how to search the container
 * and any subcontainers to find components based on name and class.
 * @author jduty
 *
 */
public class SwingContainerSearcher {

	ComponentCatalog componentCatalog = null;
	
	public SwingContainerSearcher(ComponentCatalog catalog)
	{
		this.componentCatalog = catalog;
	}
	
	
	
	
	
	public Component findComponent(String name, Class<Component> baseClass)
	{
		return searchContainers(componentCatalog.baseContainers, name, baseClass);
	}
	
	protected Component searchContainers(Collection<? extends Container> containers,String name, Class<Component> baseClass)
	{
//		 didn't find anything in this component, search any subcontainers
		Iterator<? extends Container> iterator = containers.iterator();
		while ( iterator.hasNext())
		{
			return searchContainer(iterator.next(), name, baseClass);
		}
		return null;
	}
	
	protected Component searchContainer(Container container,String name, Class<Component> baseClass)
	{
		Component[] components = container.getComponents();
		// to collect any base components
		HashSet<? extends Container> subContainers = new HashSet<? extends Container>();
		for ( int i=0;i<components.length;i++)
		{
			if( isComponentMatch(components[i], name, baseClass))
				return components[i];
			else if(components[i] instanceof Container)
				subContainers.add((Object<? extends Container>)components[i]);
		}
		
		// search any sub containers we may have found in the process.
		return searchContainers(subContainers, name, baseClass);
	}
	
	
	protected boolean isComponentMatch(Component component, String name, Class<Component> baseClass)
	{
		return ( component.getName().equals(name) && baseClass.isInstance(component));
	}
	
}
